<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 供应商名称 -->
        <div class="form-item">
            <label class="form-label">供应商名称：</label>
            <input type="text" name="supplierName"
                   class="form-input"
                   placeholder="请输入供应商名称">
        </div>
        <div class="form-item">
            <label class="form-label">船舶名称：</label>
            <input type="text" name="shipName"
                   class="form-input"
                   placeholder="请输入船舶名称">
        </div>
        <div class="form-item">
            <label class="form-label">航次号：</label>
            <input type="text" name="voyageNumber"
                   class="form-input"
                   placeholder="请输入航次号">
        </div>
        <div class="form-item">
            <label class="form-label">起始港：</label>
            <input type="text" name="startPortName"
                   class="form-input"
                   placeholder="请输入起始港">
        </div>
        <div class="form-item">
            <label class="form-label">到达港：</label>
            <input type="text" name="deliveryPortName"
                   class="form-input"
                   placeholder="请输入到达港">
        </div>

        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">任务状态：</label>
            <select class="form-input form-select" name="status">
                <option value="">全部</option>
                <option value="0">待执行</option>
                <option value="1">执行中</option>
                <option value="2">已完成</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">

        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>供应商名称</th>
            <th>船舶名称</th>
            <th>航次号</th>
            <th>起始港</th>
            <th>到达港</th>
            <th>装车数量</th>
            <th>卸车数量</th>
            <th>任务状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-vehicle-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            公路调配信息
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <div class="detail-section">
                <h4 class="detail-subtitle">调配信息</h4>
                <div class="detail-row">
                    <span class="detail-label">供应商名称：</span>
                    <span id="detail-supplierName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">起运地址：</span>
                    <span id="detail-depaturePlace" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">起运港：</span>
                    <span id="detail-depaturePort" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">交车地址：</span>
                    <span id="detail-arrivePlace" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">交车港：</span>
                    <span id="detail-arrivePort" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">装车时间：</span>
                    <span id="detail-uptime" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">卸车时间：</span>
                    <span id="detail-downtime" class="detail-value"></span>
                </div>
            </div>

            <div class="detail-section">
                <h4 class="detail-subtitle">车辆信息</h4>
                <div class="vehicle-table-container">
                    <table class="vehicle-table">
                        <thead>
                        <tr>
                            <th>批次号</th>
                            <th>运单号</th>
                            <th>车架号</th>
                            <th>品牌</th>
                            <th>型号</th>
                            <th>起始地</th>
                            <th>交车地</th>
                            <th>装车时间</th>
                            <th>交车时间</th>
                            <th>状态</th>
                        </tr>
                        </thead>
                        <tbody id="detail-vehicleList"></tbody>
                    </table>
                </div>
            </div>

            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs"></div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content" style="width: 700px;">
        <h3 class="modal-title">
            新增船舶调配 <!-- 修改标题 -->
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-add">
            <div class="form-column">
                <!-- 左列 -->
                <div class="form-col">
                    <!-- 起始港 -->
                    <div class="form-item">
                        <label>起始港：</label>
                        <input type="text" id="startPortName"
                               placeholder="请输入起始港" required>
                    </div>

                    <!-- 到达港 -->
                    <div class="form-item">
                        <label>到达港：</label>
                        <input type="text" id="deliveryPortName"
                               placeholder="请输入到达港" required>
                    </div>

                    <!-- 船舶联系电话 -->
                    <div class="form-item">
                        <label>船舶联系电话：</label>
                        <input type="tel" id="captainTel"
                               placeholder="请输入船长电话"
                               pattern="\d{11}" required>
                    </div>
                </div>

                <!-- 右列 -->
                <div class="form-col">
                    <!-- 供应商信息 -->
                    <div class="form-item">
                        <label>供应商名称：</label>
                        <input type="text" id="supplierName"
                               placeholder="请输入供应商名称" required>
                    </div>

                    <!-- 船舶名称 -->
                    <div class="form-item">
                        <label>船舶名称：</label>
                        <input type="text" id="shipName"
                               placeholder="请输入船舶名称" required>
                    </div>

                    <!-- 航次号 -->
                    <div class="form-item">
                        <label>航次号：</label>
                        <input type="text" id="voyageNumber"
                               placeholder="请输入航次号" required>
                    </div>

                    <!-- 计划装船数量 -->
                    <div class="form-item">
                        <label>计划装船数量：</label>
                        <input type="number" id="loadingNum"
                               min="1" value="1" required>
                    </div>
                </div>
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">提交</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-load">
    <div class="modal-content" style="width: 500px;">
        <h3 class="modal-title">
            车辆装车操作
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-load">
            <div class="form-column">
                <div class="form-col">
                    <div class="form-item">
                        <label>批次号：</label>
                        <input type="text" id="loadBatchNumber" required>
                    </div>
                    <div class="form-item">
                        <label>运单号：</label>
                        <input type="text" id="loadWaybillNo" required>
                    </div>
                    <div class="form-item">
                        <label>车架号：</label>
                        <input type="text" id="loadFrameNumber" required>
                    </div>
                    <div class="form-item">
                        <label>装车时间：</label>
                        <!--                        <input type="datetime-local" id="loadTime" required>-->
                        <input type="text" class="layui-input" id="loadTime" placeholder="yyyy-MM-dd HH:mm:ss">
                    </div>
                </div>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">确认装车</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-unload">
    <div class="modal-content" style="width: 500px;">
        <h3 class="modal-title">
            车辆卸车操作
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-unload">
            <div class="form-column">
                <div class="form-col">
                    <div class="form-item">
                        <label>卸车时间：</label>
                        <!--                        <input type="datetime-local" id="loadTime" required>-->
                        <input type="text" class="layui-input" id="unloadTime" placeholder="yyyy-MM-dd HH:mm:ss" required>
                    </div>
                </div>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">确认卸车</button>
            </div>
        </form>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    // 状态映射关系
    const statusMap = {
        0: '待开始',
        1: '进行中',
        2: '已完成',
    };
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');

            // 根据状态生成不同操作按钮
            let operationBtns = '';
            switch(item.status) {
                case 0: // 待开始
                    operationBtns = `
                        <button class="table-detail-btn">详情</button>
                        <button class="table-load-btn">装船</button>
                        <button class="table-delete-btn">删除</button>
                    `;
                    break;
                case 1: // 执行中
                    operationBtns = `
                        <button class="table-load-btn">装船</button>
                        <button class="table-detail-btn">详情</button>
                        <button class="table-unload-btn">卸船</button>
                    `;
                    break;
                case 2: // 已完成
                    operationBtns = `<button class="table-detail-btn">详情</button>`;
                    break;
                default:
                    operationBtns = `<button class="table-detail-btn">详情</button>`;
            }

            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.supplierName || '--'}</td>
                <td>${item.shipName || '--'}</td>
                <td>${item.voyageNumber || '--'}</td>
                <td>${item.startPortName || '--'}</td>
                <td>${item.deliveryPortName || '--'}</td>
                <td>${item.loadingNum ?? 0}</td>
                <td>${item.unloadedNumber ?? 0}</td>
                <td>${statusMap[item.status] || '未知状态'}</td>
                <td>${operationBtns}</td>
    `;

            // 绑定操作按钮事件
            const detailBtn = tr.querySelector('.table-detail-btn');
            const loadBtn = tr.querySelector('.table-load-btn');
            const unloadBtn = tr.querySelector('.table-unload-btn');
            const deleteBtn = tr.querySelector('.table-delete-btn');
            detailBtn?.addEventListener('click', () => showPlanDetail(item.id));
            // 装车操作
            loadBtn?.addEventListener('click', () => handleLoadCars(item.id));

            // 卸车操作
            unloadBtn?.addEventListener('click', () => handleUnloadCars(item.id));
            //调配完成 完成运输
            // finishBtn?.addEventListener('click', () => handleFinish(item.id));


            // 删除功能
            deleteBtn?.addEventListener('click', () => deleteDepartment(item.id));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {
        const getValue = (selector) =>
            document.querySelector(`[name="${selector}"]`).value.trim();

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            supplierName: getValue('supplierName'),
            shipName: getValue('shipName'),
            voyageNumber: getValue('voyageNumber'),
            startPortName: getValue('startPortName'),
            deliveryPortName: getValue('deliveryPortName'),
            status: getValue('status') || null, // 处理空字符串
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/shipDeploy/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        // document.querySelectorAll('.form-input').forEach(input => {
        //     if (input.type === 'text') input.value = '' // 清空文本输入
        //     if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        // });
        document.querySelectorAll('[name]').forEach(input => {
            if (input.tagName === 'SELECT') input.value = '';
            if (input.type === 'text') input.value = '';
        });
    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex'
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault()

        const formData = {
            supplierName: document.getElementById('supplierName').value,
            shipName: document.getElementById('shipName').value,
            voyageNumber: document.getElementById('voyageNumber').value,
            startPortName: document.getElementById('startPortName').value,
            deliveryPortName: document.getElementById('deliveryPortName').value,
            captainTel: document.getElementById('captainTel').value,
            loadingNum: parseInt(document.getElementById('loadingNum').value),
            status: 0 // 默认待开始状态
        }

        try {
            const response = await fetch('http://localhost:8080/shipDeploy/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();
            if(data.status===0) {
                // alert("添加成")
                document.querySelector('.modal-mask').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        } catch(err) {
            console.error('提交失败:', err)
        }
    })
    //表格函数
    // 新增以下功能函数
    async function deleteDepartment(id) {
        if (!confirm('确定要删除该部门吗？')) return;
        try {
            const res = await fetch(`http://localhost:8080/department/delete/${id}`, {
                method: 'GET'
            });
            const data = await res.json();

            if(data.status === 0) {
                alert('删除成功');
                fetchData('query');
            }
        } catch(err) {
            console.error('删除失败:', err);
        }
    }

    async function disableDepartment(id, currentStatus) {
        const newStatus = currentStatus === 1 ? 0 : 1;

        try {
            const res = await fetch(`http://localhost:8080/department/disable`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ id, status: newStatus })
            });
            const data = await res.json();

            if(data.status === 0) {
                alert(`已${newStatus === 1 ? '启用' : '禁用'}`);
                fetchData('query');
            }
        } catch(err) {
            console.error('状态修改失败:', err);
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    function updateDepartment(item) {
        // 打开编辑弹窗
        // table-edit-btn
        const form = document.getElementById('modal-form-update');
        const modal = document.querySelector('#modal-mask-update'); // 需要创建编辑弹窗结构
        // 关闭旧监听器
        if (currentEditHandler) {
            form.removeEventListener('submit', currentEditHandler);
        }

        // 填充表单数据
        let depNm= document.querySelector('#edit-depNm').value = item.depNm;
        let leader=document.querySelector('#edit-leader').value = item.leader;
        let leaderPhone=document.querySelector('#edit-phone').value = item.leaderPhone;


        // 绑定提交事件
        // 定义新处理器
        currentEditHandler = async (e) => {
            e.preventDefault();
            const formData = {
                id: item.id,
                depNm: document.getElementById('edit-depNm').value ,
                leader: document.querySelector('#edit-leader').value,
                leaderPhone: document.querySelector('#edit-phone').value
            };

            try {
                const res = await fetch('http://localhost:8080/department/update', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(formData)
                });

                const data = await res.json();
                if(data.status === 0) {
                    modal.style.display = 'none';
                    fetchData('query');
                }else if (data.status === -1){
                    modal.style.display = 'none';
                }
            } catch(err) {
                console.error('更新失败:', err);
            }
        };
        form.addEventListener('submit', currentEditHandler);
        modal.style.display = 'flex';
    }

    async function showPlanDetail(planId) {
        // try {
        const modal = document.getElementById('modal-mask-vehicle-detail');
        const res = await fetch(`http://localhost:8080/shipDeploy/detail/${planId}`);
        const response = await res.json();

        if (response.status === 0) {
            const data = response.data;

            // 其他信息填充保持不变...
            // 填充基础信息
            document.getElementById('detail-supplierName').textContent = data.fleetName || '--';
            document.getElementById('detail-depaturePlace').textContent = data.startName || '--';
            document.getElementById('detail-depaturePort').textContent = data.startPortName || '--';
            document.getElementById('detail-arrivePlace').textContent = data.deliveryName || '--';
            document.getElementById('detail-arrivePort').textContent = data.deliveryPortName || '--';
            document.getElementById('detail-uptime').textContent = data.loadingDate ? formatDateTime(data.loadingDate) : '--';
            document.getElementById('detail-downtime').textContent = data.deliveryDate ? formatDateTime(data.deliveryDate) : '--';

            // 委托车辆表格渲染
            const vehicleList = data.carList  || [];
            const vehicleTbody = document.getElementById('detail-vehicleList');

            if (vehicleList.length > 0) {
                vehicleTbody.innerHTML = vehicleList.map(vehicle => `
                    <tr>
                        <td>${vehicle.batchNumber || '--'}</td>
                        <td>${vehicle.waybillNo || '--'}</td>
                        <td>${vehicle.frameNumber || '--'}</td>
                        <td>${vehicle.brand || '--'}</td>
                        <td>${vehicle.model || '--'}</td>
                        <td>${vehicle.startName || '--'}</td>
                        <td>${vehicle.deliveryName || '--'}</td>
                        <td>${vehicle.loadingDate ? formatDateTime(vehicle.loadingDate) : '--'}</td>
                        <td>${vehicle.deliveryDate ? formatDateTime(vehicle.deliveryDate) : '--'}</td>
                        <td>${vehicleStatusMap[vehicle.state] || '未知状态'}</td>
                    </tr>
                `).join('');
            } else {
                vehicleTbody.innerHTML = `<tr><td colspan="10" style="text-align:center">暂无车辆信息</td></tr>`;
            }

            // 操作记录渲染
            const logs = data.operateRecordList || [];
            const logsContainer = document.getElementById('detail-operationLogs');
            if (logs.length > 0) {
                logsContainer.innerHTML = logs.map(log => `
                    <div class="log-item">
                    <div class="log-time">
                        ${log.createTime ? formatDateTime(log.createTime) : '--'}
                    </div>
                    <div>
                        <span class="log-type ">
                            ${log.operateType || '--'}
                        </span>
                    </div>
                    <div class="log-remark">
                        ${log.remark || '无备注信息'}
                    </div>
                </div>
                `).join('');
            } else {
                logsContainer.innerHTML = `
                <div class="no-logs">暂无操作记录</div>
            `;
            }


            modal.style.display = 'flex';
            currentDetailModal = modal;
        }
        // } catch (err) {
        //     console.error('详情加载失败:', err);
        //     alert('详情加载失败');
        // }
    }
    // 装车
    // 新增操作处理函数
    async function handleLoadCars(taskId) {
        currentTaskId = taskId;

        // 清空表单
        document.getElementById('modal-form-load').reset();

        // 显示弹窗
        loadModal.style.display = 'flex';
    }
    // 卸车
    async function handleUnloadCars(taskId) {
        currentTaskId = taskId;

        // 清空表单
        document.getElementById('modal-form-unload').reset();

        // 显示弹窗
        loadModal2.style.display = 'flex';
    }
    // 时间格式化函数
    function formatDateTime(timeStr) {
        if (!timeStr) return '--';
        // 处理ISO格式时间
        const date = new Date(timeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        }).replace(/\//g, '-');
    }

    // 状态映射关系（新增车辆状态）
    const vehicleStatusMap = {
        0: '已分配',
        1: '运输中',
        2: '已交车',
    };

    // 添加装车弹窗控制逻辑
    let currentTaskId = null;

    // 初始化装车弹窗
    const loadModal = document.getElementById('modal-mask-load');
    const loadModal2 = document.getElementById('modal-mask-unload');
    document.querySelectorAll('#modal-mask-load .modal-close-btn, #modal-mask-load .btn-close,#modal-mask-unload .btn-close,#modal-mask-unload .modal-close-btn').forEach(btn => {
        btn.addEventListener('click', () => loadModal.style.display = 'none');
        btn.addEventListener('click', () => loadModal2.style.display = 'none');
    });

    // 装车表单提交处理
    document.getElementById('modal-form-load').addEventListener('submit', async (e) => {
        e.preventDefault();
        const timeInput = document.getElementById('loadTime').value;
        const formattedTime = formatDateTimeForSubmit(timeInput); // 新增格式化函数
        // 构造请求数据
        const formData = {
            id: currentTaskId,
            startTime: formattedTime,
            carList: [{
                batchNumber: document.getElementById('loadBatchNumber').value,
                waybillNo: document.getElementById('loadWaybillNo').value,
                frameNumber: document.getElementById('loadFrameNumber').value,
            }]
        };

        // 客户端验证
        if (!validateLoadForm(formData)) return;

        try {
            const response = await fetch('http://localhost:8080/shipDeploy/loadCars', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const result = await response.json();
            if (result.status === 0) {
                alert('装车成功');
                loadModal.style.display = 'none';
                fetchData('query');
            } else {
                // showError(result.message || '装车操作失败');
                console.log("装车操作失败")
            }
        } catch (error) {
            console.error('装车请求失败:', error);
            console.log("装车操作失败")
        }
    });
    document.getElementById('modal-form-unload').addEventListener('submit', async (e) => {
        e.preventDefault();
        const timeInput = document.getElementById('unloadTime').value;
        const formattedTime = formatDateTimeForSubmit(timeInput); // 新增格式化函数
        // 构造请求数据
        const formData = {
            id: currentTaskId,
            endTime: formattedTime
        };


        try {
            const response = await fetch('http://localhost:8080/shipDeploy/unloadCars', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const result = await response.json();
            if (result.status === 0) {
                alert('装车成功');
                loadModal.style.display = 'none';
                fetchData('query');
            } else {
                // showError(result.message || '装车操作失败');
                console.log("装车操作失败")
            }
        } catch (error) {
            console.error('装车请求失败:', error);
            console.log("装车操作失败")
        }
    });
    // 表单验证方法
    function validateLoadForm(data) {
        const validations = [
            { check: !data.id, message: '任务ID不能为空' },
            { check: !data.carList?.[0]?.batchNumber, message: '批次号不能为空' },
            { check: !data.carList?.[0]?.waybillNo, message: '运单号不能为空' },
            { check: !data.carList?.[0]?.frameNumber, message: '车架号不能为空' }
        ];

        const error = validations.find(v => v.check);
        if (error) {
            alert(error.message);
            return false;
        }
        return true;
    }
    layui.use(function(){
        var laydate = layui.laydate;
        // 日期时间选择器
        laydate.render({
            elem: '#loadTime',
            type: 'datetime'
        });
        laydate.render({
            elem: '#unloadTime',
            type: 'datetime'
        });
    });

    // 新增时间格式化函数
    function formatDateTimeForSubmit(dateString) {
        const date = new Date(dateString);
        const pad = (num) => num.toString().padStart(2, '0');

        return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ` +
            `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    }
</script>
</body>
</html>